package com.swt.gap.controller;

import com.swt.gap.common.PageResult;
import com.swt.gap.model.vo.ResultStatisticsVO;
import com.swt.gap.model.vo.achievementcenter.AchievementInfoListVO;
import com.swt.gap.model.vo.achievementcenter.AchievementListVO;
import com.swt.gap.model.vo.achievementcenter.AchievementPassword;
import com.swt.gap.model.vo.achievementcenter.AddOrUpdateAchievementModel;
import com.swt.gap.model.vo.AchievementInfoVO;
import com.swt.gap.service.AchievementService;
import com.swt.gap.util.UserLoginUtils;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**result-model
 * @author tyh
 * @date 2020/5/11 17:48
 */

@Api(tags = "502. 战果相关")
@RestController
@RequestMapping("/achievement")
@Slf4j
public class AchievementController {

    private final AchievementService achievementService;

    public AchievementController(AchievementService achievementService) {
        this.achievementService = achievementService;
    }


    @PostMapping
    @ApiOperation(value = "战果制作或修改", notes = "战果制作或修改")
    @ApiImplicitParam(name = "achievement", dataType = "AddOrUpdateAchievementModel",paramType = "body", value = "战果信息")
    @ApiResponses({@ApiResponse(code = 201, message = "制作成功"),
                    @ApiResponse(code = 409, message = "已重名"),
                    @ApiResponse(code = 400, message = "非法请求"),
                    @ApiResponse(code = 200, message = "修改成功")
    })
    public ResponseEntity<Object> addOrUpdateAchievement(@RequestBody AddOrUpdateAchievementModel achievement){
        Integer userId = UserLoginUtils.getUserId();

        //对战果名的校验
        String achievementName = achievement.getAchievementName();
        Integer achievementId = achievement.getAchievementId();
        if(StringUtils.isNotBlank(achievementName)){
            achievementName = achievementName.trim();
            if(achievementName.length() > 50){
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("名称长度不能超过50");
            }
            achievement.setAchievementName(achievementName);
        }else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("名称不能为空");
        }
        //判断重名
        Boolean isRepeat = achievementService.judgeName(userId,achievementName, achievementId);
        if (isRepeat) {
            return ResponseEntity.status(HttpStatus.CONFLICT).body("战果名重名，不可用");
        }

        if(achievementId == null || achievementId < 1){
            //新增
            int newAchievementId = achievementService.addAchievement(userId,achievement);
            return ResponseEntity.status(HttpStatus.CREATED).body(newAchievementId);
        }else {
            return ResponseEntity.ok(achievementService.updateAchievement(achievement));
        }


    }

    @GetMapping("/{achievementId}")
    @ApiOperation(value = "获取战果详情", notes = "获取战果详情")
    @ApiImplicitParam(name = "achievementId", dataType = "int",paramType = "path", value = "战果Id")
    @ApiResponses({@ApiResponse(code = 200, message = "ok", response = AchievementInfoVO.class)})
    public ResponseEntity<AchievementInfoVO> getAchievement(@PathVariable Integer achievementId){
        return ResponseEntity.ok(achievementService.getAchievementInfo(achievementId));
    }

//    @GetMapping("/list")
//    @ApiOperation(value = "获取用户的战果列表", notes = "获取用户的战果列表")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "keyword", dataType = "String",paramType = "query", value = "关键字")/*,
//            @ApiImplicitParam(name = "orderType", required = true, dataType = "int",paramType = "query", value = "排序方式 默认为0：ID排序 1：时间降序 2：时间升序 3：名称降序 4：名称升序"),
//            @ApiImplicitParam(name = "pageNum", required = true, dataType = "int", paramType = "query", value = "当前页"),
//            @ApiImplicitParam(name = "pageSize", required = true, dataType = "int", paramType = "query", value = "每页的条数")*/
//    })
//    @ApiResponses({@ApiResponse(code = 200, message = "ok", response = AchievementInfoVO.class)})
//    public ResponseEntity getAchievementLists(String keyword/*,int orderType,int pageNum,int pageSize*/){
//        int userId = UserLoginUtils.getUserId();
//        /*if (StringUtils.isBlank(keyword)){
//
//        }*/
//        return ResponseEntity.ok(achievementService.getAchievementList(userId,keyword));
//
//        //return ResponseEntity.ok(achievementService.searchAchievement(userId,keyword/*,orderType,pageNum,pageSize*/));
//    }

    @DeleteMapping("/delete")
    @ApiOperation(value = "删除战果", notes = "删除战果")
    @ApiImplicitParam(name = "achievementIds", dataType = "int",paramType = "body", value = "战果Id")
    @ApiResponses({@ApiResponse(code = 200, message = "ok"),
                    @ApiResponse(code = 400,message = "参数非法")})
    public ResponseEntity<Object> deleteAchievement(@RequestBody int[] achievementIds){
        if(achievementIds == null || achievementIds.length <= 0){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("参数非法");
        }
        Integer userId = UserLoginUtils.getUserId();
        for (Integer achievementId : achievementIds) {
            if (!achievementService.hasWritePermission(userId, achievementId)) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body("无操作权限");
            }
        }
        return ResponseEntity.ok(achievementService.deleteAchievement(achievementIds));
    }


    @Deprecated
    @GetMapping
    @ApiOperation(value = "获取用户的战果列表, 过时", notes = "获取用户的战果列表,   过时")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keyword", dataType = "String",paramType = "query", value = "关键字")})
    @ApiResponses({@ApiResponse(code = 200, message = "ok", response = AchievementInfoVO.class, responseContainer = "List")})
    public ResponseEntity<List<AchievementListVO>> listAchievement(String keyword){
        int userId = UserLoginUtils.getUserId();
        return ResponseEntity.ok(achievementService.listAchievement(userId, keyword));

    }


    @GetMapping("/result-statistics")
    @ApiOperation(value = "分析结果统计", notes = "分析结果统计")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "field", dataType = "String",paramType = "query", value = "统计字段"),
            @ApiImplicitParam(name = "resultId", dataType = "Integer",paramType = "query", value = "结果id")
    })
    @ApiResponses({@ApiResponse(code = 200, message = "ok", response = ResultStatisticsVO.class, responseContainer = "List")})
    public ResponseEntity<List<ResultStatisticsVO>> statisticsResult(String field, Integer resultId){

        return ResponseEntity.ok(achievementService.statisticsResult(field, resultId));
    }

    @GetMapping("/v3")
    @ApiOperation(value = "获取战果列表, 新版v3", notes = "获取战果列表, 新版v3")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keyword", dataType = "String",paramType = "query", value = "关键字"),
            @ApiImplicitParam(name = "pageNum", dataType = "int", paramType = "query", value = "当前页"),
            @ApiImplicitParam(name = "pageSize", dataType = "int", paramType = "query", value = "每页的条数")
    })
    @ApiResponses({@ApiResponse(code = 200, message = "ok", response = PageResult.class, responseContainer = "List")})
    public ResponseEntity<PageResult<AchievementInfoListVO>> listAchievement3(@RequestParam String keyword,
                                                                              @RequestParam(required = false) Integer pageNum,
                                                                              @RequestParam(required = false) Integer pageSize){
        int userId = UserLoginUtils.getUserId();
        return ResponseEntity.ok(achievementService.listAchievement3(userId, keyword, pageNum, pageSize));

    }



    @PostMapping("/password")
    @ApiOperation(value = "设置或者更新战果的密码", notes = "设置或者更新战果的密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "achievementPassword", dataType = "AchievementPassword", paramType = "body")
    })
    @ApiResponse(code = 200, message = "ok", response = String.class)
    public ResponseEntity<String> addOrUpdatePassword(@RequestBody AchievementPassword achievementPassword) {
        Integer userId = UserLoginUtils.getUserId();
        for (Integer achievementId : achievementPassword.getAchievementIds()) {
            if (!achievementService.hasWritePermission(userId, achievementId)) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body("无操作权限");
            }
        }
        return ResponseEntity.ok(achievementService.updatePassword(achievementPassword).toString());
    }

    @DeleteMapping("/password")
    @ApiOperation(value = "删除数据战果的密码", notes = "删除数据战果的密码")
    @ApiImplicitParams({
//            @ApiImplicitParam(name = "achievementIds", dataType = "int", allowMultiple = true, paramType = "query")
    })
    @ApiResponse(code = 200, message = "ok", response = String.class)
    public ResponseEntity<String> deleteDataPassword(@RequestParam List<Integer> achievementIds) {
        Integer userId = UserLoginUtils.getUserId();
        for (Integer achievementId : achievementIds) {
            if (!achievementService.hasWritePermission(userId, achievementId)) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body("无操作权限");
            }
        }
        AchievementPassword achievementPassword = new AchievementPassword();
        achievementPassword.setAchievementIds(achievementIds);
        return ResponseEntity.ok(achievementService.updatePassword(achievementPassword).toString());
    }

    @GetMapping("/read-permission")
    @ApiOperation(value = "获取读权限", notes = "获取读权限" )
    @ApiImplicitParams({
            @ApiImplicitParam(name = "achievementId", dataType = "int", paramType = "query", value = "achievementId"),
            @ApiImplicitParam(name = "password", dataType = "string", paramType = "query", value = "密码")
    })
    @ApiResponse(code = 200, message = "ok", response = Boolean.class)
    public ResponseEntity<Boolean> getReadPerm(@RequestParam Integer achievementId, @RequestParam String password){
        return ResponseEntity.ok(achievementService.getReadPerm(achievementId, password));
    }
}
